package com.xinqi.modules.sys.appversion.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.enums.YesNoNumberEnum;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.core.utils.StringUtils;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.sys.appversion.convert.AppVersionConvert;
import com.xinqi.modules.sys.appversion.domain.AppVersionEntity;
import com.xinqi.modules.sys.appversion.dto.req.AppVersionCreateDTO;
import com.xinqi.modules.sys.appversion.dto.req.AppVersionDeleteDTO;
import com.xinqi.modules.sys.appversion.dto.req.AppVersionHtmlQueryDTO;
import com.xinqi.modules.sys.appversion.dto.req.AppVersionLatestQueryDTO;
import com.xinqi.modules.sys.appversion.dto.req.AppVersionQueryDTO;
import com.xinqi.modules.sys.appversion.dto.req.AppVersionUpdateDTO;
import com.xinqi.modules.sys.appversion.dto.rsp.AppVersionResultDTO;
import com.xinqi.modules.sys.appversion.manager.AppVersionManager;
import com.xinqi.modules.sys.appversion.service.AppVersionService;
import com.xinqi.modules.sys.util.FileUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 版本记录列表服务层实现
 *
 * @author: linkai
 * @date: 2023/04/27
 */
@Validated
@Service("appVersionService")
@RequiredArgsConstructor
public class AppVersionServiceImpl implements AppVersionService {
    private final AppVersionConvert appVersionConvert;
    private final AppVersionManager appVersionManager;

    /**
     * 分页查询 版本记录列表数据
     */
    @Override
    @DS("slaver")
    public PageInfo<AppVersionResultDTO> page(Param pageable, AppVersionQueryDTO query) {
        IPage<AppVersionEntity> page = appVersionManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, appVersionConvert::convert);
    }

    /**
     * 分页查询 版本记录列表数据
     */
    @Override
    @DS("slaver")
    public PageInfo<AppVersionResultDTO> page(Param pageable, AppVersionHtmlQueryDTO query) {
        LambdaQueryWrapper<AppVersionEntity> wrapper = Queries.lambda();
        Queries.accept(query.getChannel(), v -> wrapper.eq(AppVersionEntity::getChannel, v));
        Queries.accept(query.getClientType(), v -> wrapper.eq(AppVersionEntity::getClientType, v));
        wrapper.orderByDesc(AppVersionEntity::getVersionCode);
        IPage<AppVersionEntity> page = appVersionManager.page(Pages.page(pageable), wrapper);
        return Pages.convert(page, appVersionConvert::convert);
    }

    /**
     * 查询 版本记录列表数据
     */
    @Override
    public List<AppVersionResultDTO> find(AppVersionQueryDTO query) {
        return appVersionManager.list(wrapper(query)).stream()
            .map(appVersionConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<AppVersionEntity> wrapper(AppVersionQueryDTO query) {
        LambdaQueryWrapper<AppVersionEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(AppVersionEntity::getId, v));
        Queries.accept(query.getVersionCode(), v -> wrapper.eq(AppVersionEntity::getVersionCode, v));
        Queries.accept(query.getIsForced(), v -> wrapper.eq(AppVersionEntity::getIsForced, v));
        Queries.accept(query.getChannel(), v -> wrapper.eq(AppVersionEntity::getChannel, v));
        Queries.accept(query.getClientType(), v -> wrapper.eq(AppVersionEntity::getClientType, v));
        return wrapper;
    }

    /**
     * 根据id查询 版本记录列表数据
     */
    @Override
    public AppVersionResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(appVersionManager.findById(id)).map(appVersionConvert::convert).orElse(null);
    }

    /**
     * 新增 版本记录列表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(AppVersionCreateDTO dto) {
        AppVersionEntity entity = appVersionConvert.create(dto);
        if (StringUtils.isNotEmpty(entity.getDownloadUrl())) {
            entity.setSize(FileUtils.clacFileSize(entity.getDownloadUrl()));
        }
        appVersionManager.save(entity);
        return entity.getId();
    }

    /**
     * 根据id修改 版本记录列表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(AppVersionUpdateDTO dto) {
        Optional.ofNullable(appVersionManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        AppVersionEntity entity = appVersionConvert.update(dto);
        return appVersionManager.updateById(entity);
    }

    /**
     * 根据id删除 版本记录列表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return appVersionManager.removeById(id);
    }

    /**
     * 根据id删除 版本记录列表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(AppVersionDeleteDTO dto) {
        return deleteById(dto.getId());
    }

    @Override
    public AppVersionResultDTO latestVersion(AppVersionLatestQueryDTO query) {
        LambdaQueryWrapper<AppVersionEntity> wrapper = Queries.lambda();
        wrapper.eq(StringUtils.isNotEmpty(query.getChannel()), AppVersionEntity::getChannel, query.getChannel())
            .eq(Objects.nonNull(query.getClientType()), AppVersionEntity::getClientType, query.getClientType())
            .gt(Objects.nonNull(query.getVersionCode()), AppVersionEntity::getVersionCode, query.getVersionCode())
            .orderByDesc(AppVersionEntity::getVersionCode)
            .orderByDesc(AppVersionEntity::getCreateTime);
        List<AppVersionEntity> list = appVersionManager.list(wrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            AppVersionEntity newAppVersion = list.get(0);
            for (AppVersionEntity version : list) {
                if (Objects.equals(YesNoNumberEnum.YES.getCode(), version.getIsForced())) {
                    newAppVersion.setIsForced(YesNoNumberEnum.YES.getCode());
                }
            }
            return appVersionConvert.convert(newAppVersion);
        } else {
            wrapper = Queries.lambda();
            wrapper.eq(StringUtils.isNotEmpty(query.getChannel()), AppVersionEntity::getChannel, query.getChannel())
                .eq(Objects.nonNull(query.getClientType()), AppVersionEntity::getClientType, query.getClientType())
                .orderByDesc(AppVersionEntity::getVersionCode)
                .orderByDesc(AppVersionEntity::getCreateTime)
                .last("LIMIT 1");
            AppVersionEntity version = appVersionManager.getOne(wrapper);
            return appVersionConvert.convert(version);
        }
    }

}
